package com.tsingsoft;

import com.tsingsoft.wslogs.domain.LoggerMessage;
import com.tsingsoft.wslogs.handle.LoggerQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ========================
 *
 * @author bask
 * @date : 2021/1/8 17:12
 * Version: 1.0
 * ========================
 */
@SpringBootApplication
@EnableScheduling
@EnableWebSocketMessageBroker
public class WsLogsApplication {
    private static final Logger log = LoggerFactory.getLogger(WsLogsApplication.class);
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    int info = 1;

    public WsLogsApplication() {
    }

    public static void main(String[] args) {
        SpringApplication.run(WsLogsApplication.class, args);
    }

    @Scheduled(
            fixedRate = 1000L
    )
    public void outputLogger() {
        log.info("测试日志输出" + this.info++);
    }

    @PostConstruct
    public void pushLogger() {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Runnable runnable = new Runnable() {
            public void run() {
                while(true) {
                    try {
                        LoggerMessage log = LoggerQueue.getInstance().poll();
                        if (log != null && WsLogsApplication.this.messagingTemplate != null) {
                            WsLogsApplication.this.messagingTemplate.convertAndSend("/topic/pullLogger", log);
                        }
                    } catch (Exception var2) {
                        var2.printStackTrace();
                    }
                }
            }
        };
        executorService.submit(runnable);
        executorService.submit(runnable);
    }
}
